package com.omesoft.hksnore.util.omeview;


import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_SleepDetail;

import java.util.ArrayList;
import java.util.List;

/**
 * 圆环
 *
 * @author omesoft_lgc
 * @date 2016-3-4 下午2:27:17
 */
public class ColorArcProgressBar extends View {

    private int mWidth;
    private int mHeight;
    // 直径
    private int diameter = 500;
    // 圆心
    private float centerX;
    private float centerY;

    private Paint allArcPaint;
    private Paint progressPaint;
    private Paint vTextPaint;
    private Paint hintPaint;
    private Paint degreePaint;
    private Paint curSpeedPaint;

    private RectF bgRect;
    private RectF progressRect;

    private ValueAnimator progressAnimator;
    private PaintFlagsDrawFilter mDrawFilter;
    private SweepGradient sweepGradient;
    private Matrix rotateMatrix;

    private float startAngle = 135;//开始角度
    private float sweepAngle = 270;//总角度数
    private float sweepAngle2 = 130;
    private float currentAngle = 0;
    private float mSweepAnglePer;
    private float lastAngle;
    private int[] colors = new int[]{Color.GREEN, Color.YELLOW, Color.RED, Color.RED};
    private int[] colors2 = new int[]{Color.GREEN, Color.YELLOW, Color.RED, Color.RED};
    private float maxValues = 60;
    private float curValues = 0;
    private float bgArcWidth = dipToPx(2);
    private float progressWidth = dipToPx(10);
    private float textSize = dipToPx(14);
    private float hintSize = dipToPx(25);
    private float curSpeedSize = dipToPx(13);
    private int aniSpeed = 1000;
    private float longdegree = dipToPx(13);
    private float shortdegree = dipToPx(5);
    private final int DEGREE_PROGRESS_DISTANCE = dipToPx(8);
    private String hintColor = "#AD9D6A";
    private String longDegreeColor = "#2D91F6";
    private String shortDegreeColor = "#2D91F6";
    private String bgArcColor = "#A89669";
    private boolean isShowCurrentSpeed = true;
    private String hintString = "Km/h";
    private boolean isNeedTitle;
    private boolean isNeedUnit;
    private boolean isNeedDial;
    private boolean isNeedContent;
    private boolean isMoveEnd = false;
    private String titleString;
    private int bar_type = 1;

    private Paint mPaint1; // 背景画笔

    private Canvas canvas;

    // sweepAngle / maxValues 的值
    private float k;

    private float weight_Target;
    private float target_CurrentAngle = 0;

    private boolean isLoadEnd = false;
    private int isLoadCount = 0;
    private Paint mArcPaint;

    private String startTime = " ", endTime = " ";
    private long startDate;
    private long endDate;
    BarAnimation anim;
    private List<Medix_Pub_Sync_SleepDetail> sleepDetailList;

    public ColorArcProgressBar(Context context) {
        super(context, null);
        initView();
    }

    public ColorArcProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        initCofig(context, attrs);
        initView();
    }

    public ColorArcProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCofig(context, attrs);
        initView();
    }

    /**
     * 初始化布局配置
     *
     * @param context
     * @param attrs
     */
    private void initCofig(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorArcProgressBar);
        int color1 = a.getColor(R.styleable.ColorArcProgressBar_front_color1, getResources().getColor(R.color.report_bar_current_values));
        int color2 = a.getColor(R.styleable.ColorArcProgressBar_front_color2, color1);
        int color3 = a.getColor(R.styleable.ColorArcProgressBar_front_color3, color1);
        colors = new int[]{color1, color2, color3, Color.RED};
        colors2 = new int[]{color1, color2, color2};
        sweepAngle = a.getInteger(R.styleable.ColorArcProgressBar_total_engle, 270);
        bgArcWidth = a.getDimension(R.styleable.ColorArcProgressBar_back_width, dipToPx(2));
        progressWidth = a.getDimension(R.styleable.ColorArcProgressBar_front_width, dipToPx(19));
        isNeedTitle = a.getBoolean(R.styleable.ColorArcProgressBar_is_need_title, false);
        isNeedContent = a.getBoolean(R.styleable.ColorArcProgressBar_is_need_content, false);
        isNeedUnit = a.getBoolean(R.styleable.ColorArcProgressBar_is_need_unit, false);
        isNeedDial = a.getBoolean(R.styleable.ColorArcProgressBar_is_need_dial, false);
        hintString = a.getString(R.styleable.ColorArcProgressBar_string_unit);
        titleString = a.getString(R.styleable.ColorArcProgressBar_string_title);
        curValues = a.getFloat(R.styleable.ColorArcProgressBar_current_value, 0);
        maxValues = a.getFloat(R.styleable.ColorArcProgressBar_max_value, 60);
        setCurrentValues(curValues, 0);
        setMaxValues(maxValues);
        a.recycle();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mWidth = (int) (2 * longdegree + progressWidth + diameter + 2 * DEGREE_PROGRESS_DISTANCE);
        mHeight = (int) (2 * longdegree + progressWidth + diameter + 2 * DEGREE_PROGRESS_DISTANCE);
        setMeasuredDimension(mWidth, mHeight);
    }

    private void initView() {
        L.e("调用顺序sinitView2");
        sleepDetailList = new ArrayList<>();
        diameter = (int) (2.4 * getScreenWidth() / 5);
        // 弧形的矩阵区域
        bgRect = new RectF();
        bgRect.top = progressWidth / 2 + DEGREE_PROGRESS_DISTANCE;
        bgRect.left = progressWidth / 2 + DEGREE_PROGRESS_DISTANCE;
        bgRect.right = diameter + (longdegree * 2 + progressWidth / 2 + DEGREE_PROGRESS_DISTANCE);
        bgRect.bottom = diameter + (longdegree * 2 + progressWidth / 2 + DEGREE_PROGRESS_DISTANCE);

        // 圆心
        centerX = (2 * longdegree + progressWidth + diameter + 2 * DEGREE_PROGRESS_DISTANCE) / 2;
        centerY = (2 * longdegree + progressWidth + diameter + 2 * DEGREE_PROGRESS_DISTANCE) / 2;

        // 外部刻度线
        degreePaint = new Paint();
        degreePaint.setColor(Color.parseColor(longDegreeColor));

        // 整个弧形
        allArcPaint = new Paint();
        allArcPaint.setAntiAlias(true);
        allArcPaint.setStyle(Style.STROKE);
        allArcPaint.setStrokeWidth(bgArcWidth);
        allArcPaint.setColor(Color.parseColor(bgArcColor));
        allArcPaint.setStrokeCap(Paint.Cap.ROUND);

        // 当前进度的弧形
        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);
        progressPaint.setStyle(Style.STROKE);
        progressPaint.setStrokeCap(Paint.Cap.BUTT);
        progressPaint.setStrokeWidth(progressWidth);
        progressPaint.setColor(Color.GREEN);

        // 内容显示文字
        vTextPaint = new Paint();
        vTextPaint.setTextSize(textSize);
        // vTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
        vTextPaint.setColor(Color.parseColor(hintColor));
        vTextPaint.setTextAlign(Align.CENTER);

        // 显示单位文字
        hintPaint = new Paint();
        hintPaint.setTextSize(hintSize);
        hintPaint.setTypeface(Typeface.DEFAULT_BOLD);
        hintPaint.setColor(Color.parseColor(hintColor));
        hintPaint.setTextAlign(Align.CENTER);

        // 显示标题文字
        curSpeedPaint = new Paint();
        curSpeedPaint.setTextSize(curSpeedSize);
        curSpeedPaint.setColor(Color.parseColor(hintColor));
        curSpeedPaint.setTextAlign(Align.CENTER);

        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        rotateMatrix = new Matrix();
        //
        mPaint1 = new Paint();
        mPaint1.setAntiAlias(true);
        mPaint1.setDither(true);// 防抖动
        mPaint1.setFilterBitmap(true);//


        mArcPaint = new Paint();
        mArcPaint.setColor(getResources().getColor(R.color.text_color));
        mArcPaint.setAntiAlias(true);
        mArcPaint.setTextAlign(Align.LEFT);
        mArcPaint.setStyle(Style.FILL);
        mArcPaint.setStrokeWidth(progressWidth * 0.8f);
        anim = new BarAnimation();
        anim.setDuration(500);
    }


    /**
     * 画图控制
     * 控制view的所有显示内容
     */
    @Override
    protected void onDraw(Canvas canvas) {
        // 抗锯齿
        this.canvas = canvas;
        canvas.setDrawFilter(mDrawFilter);
        if (type == 0) {

            sweepGradient = new SweepGradient(centerX, centerY, colors2, null);
        } else {
            /**
             * 蓝色：BMI<18.5，原体重（wOld）<身高^2*18.5 绿色：18.5<=BMI<24 黄色：24<=BMI<32
             * 红色：32<=BMI
             */
//			Log.e("xx", "------------min_bmi " + min_bmi);
//			Log.e("xx", "----------max_bmi " + max_bmi);
            if (min_bmi < 18.5) {
                if (max_bmi <= 24) {
                    sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.5f,
                            0.9f, 1f});
                } else if (max_bmi <= 32) {

                    sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.4f,
                            0.6f, 1f});
                } else {
                    sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.3f,
                            0.5f, 0.8f});
                }
            } else if (min_bmi >= 18.5 && min_bmi < 24) {

                if (max_bmi <= 32) {
                    sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.0f,
                            0.0f, 1f});
                } else {
                    sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.0f,
                            0.5f, 0.6f});
                }
            } else if (min_bmi >= 24 && min_bmi < 32) {

                sweepGradient = new SweepGradient(centerX, centerY, colors, new float[]{0.0f, 0.0f, 0.0f,
                        0.6f});
            }

        }
        // 整个弧
        canvas.drawArc(bgRect, startAngle, mSweepAnglePer, false, allArcPaint);
        Log.e("allArcPaint: ", "startAngle: " + startAngle + "    currentAngle  " + currentAngle);

        // 设置渐变色
        rotateMatrix.setRotate(sweepAngle2, centerX, centerY);
        if (sweepGradient == null) {
            sweepGradient = new SweepGradient(centerX, centerY, colors, null);
        }
        sweepGradient.setLocalMatrix(rotateMatrix);
        progressPaint.setShader(sweepGradient);//着色器

        // 画鼾声所占比例

        if (sleepDetailList != null && sleepDetailList.size() > 0) {
            long tempTime = 0;
            long tenMIN = 590;//十分钟秒数
            for (int i = 0; i < sleepDetailList.size(); i++) {
                if (sleepDetailList.get(i).getSnoreCount() > 0) {
                    long snoreStart = MyDateUtil.stringTOlongDate(sleepDetailList.get(i).getCreatedDate());
                    float initAngle = (((snoreStart - startDate) / 60) / maxValues) * mSweepAnglePer;//计算起始角度=(打鼾开始秒数-监测开始秒数)*总弧长度数  得出在整个环形中的起始位置
                    float currenAngle = (10 / maxValues) * mSweepAnglePer;//计算打鼾时长在view中所占的角度，（分钟数/总分钟数）*总弧长角度
                    /**
                     * 监测未结束时主表数据已经插入到数据库，
                     * 子表每两分钟一条，用不正常的方式结束监测会出现
                     * 打鼾时间大于监测停止时间的情况
                     * 加此判断防止画图错误
                     * */
                    if (snoreStart < endDate) {
                        if (snoreStart > tempTime) {
                            if (initAngle + currenAngle > sweepAngle) {//判断画图是否超出扇形范围，超出则把图填满即可

                                canvas.drawArc(bgRect, startAngle + initAngle, sweepAngle - initAngle, false, progressPaint);
                                Log.e("drawArc","startAngle="+ startAngle+"    currenAngle="+currenAngle+"    initAngle="+initAngle+"   initAngle + currenAngle="+(initAngle + currenAngle));
                            } else {

                                canvas.drawArc(bgRect, startAngle + initAngle, currenAngle, false, progressPaint);
                                Log.e("drawArc","startAngle="+ startAngle+"    currenAngle="+currenAngle+"    initAngle="+initAngle+"   initAngle + currenAngle="+(initAngle + currenAngle));
                            }
                            tempTime = snoreStart + tenMIN;//下一个打鼾时间大于10分钟才画图


                        }
                    }

                }
            }
        }else {
            canvas.drawArc(bgRect, startAngle , sweepAngle , false, allArcPaint);

        }

        /**
         * 画文字
         */
        vTextPaint.setColor(Color.parseColor(hintColor));
        if (startTime != null && endTime != null) {
            Log.i("dtosDetail",startTime+"    "+endTime );
            vTextPaint.setTextSize(dipToPx(12));
            canvas.drawText(startTime, mWidth / 4 - textSize / 2, (float) (mHeight * 0.90 + textSize / 4), vTextPaint);
            canvas.drawText(endTime, (float) (mWidth * 0.75 + textSize / 2), (float) (mHeight * 0.90 + textSize / 4), vTextPaint);

        }

    }

    /**
     * 设置最大值
     *
     * @param maxValues
     */
    public void setMaxValues(float maxValues) {
        this.maxValues = maxValues;
        k = sweepAngle / maxValues;
    }

    /**
     * 设置当前值
     *
     * @param currentValues
     */
    private int type = 0;
    private float visValue = 0;

    /**
     * @param currentValues 当前值
     * @param _type         类型
     */
    public void setCurrentValues(float currentValues, int _type) {
        this.curValues = currentValues;
        if (currentValues > maxValues) {
            currentValues = maxValues;
        }
        if (currentValues < 0) {
            currentValues = 0;
        }
        currentValues2 = currentValues;
        isMoveEnd = true;
        lastAngle = currentAngle;
        type = _type;
        currentAngle = currentValues * k;
        Log.i("currentAngle", "setCurrentValues: " + currentAngle + "  " + currentValues + "  " + k);

        // setAnimation(lastAngle, currentValues * k, aniSpeed);
    }

    float _newValue = 0;
    float min_bmi = 0;
    float max_bmi = 0;

    boolean isNotHasTarget = true;

    /**
     * @param temp1           当前目标的位置
     * @param _type           类型
     * @param newValue        显示的值
     * @param currentValues   当前 体重的 位置
     * @param _max            最大 bmi
     * @param _min            最小 bmi
     * @param _isNotHasTarget 是否设置 目标体重
     */
    public void setCurrentValues(float temp1, int _type, float newValue, float currentValues, float _max,
                                 float _min, boolean _isNotHasTarget) {
        if (currentValues > maxValues) {
            currentValues = maxValues;
        }
        if (currentValues < 0) {
            currentValues = 0;
        }
        isNotHasTarget = _isNotHasTarget;
        // this.weight_Target = _weight_Target;
        min_bmi = _min;
        max_bmi = _max;
        currentValues2 = currentValues;
        isMoveEnd = true;
        this.curValues = newValue;
        lastAngle = currentAngle;
        type = _type;
        /**
         * 处理旋转值
         */
        _newValue = newValue;
        currentAngle = currentValues * k;
        target_CurrentAngle = temp1 * k;

        invalidate();
        setAnimation(lastAngle, currentValues * k, aniSpeed);
    }

    float currentValues2 = 135;

    /**
     * 设置整个圆弧宽度
     *
     * @param bgArcWidth
     */
    public void setBgArcWidth(int bgArcWidth) {
        this.bgArcWidth = bgArcWidth;
    }

    /**
     * 设置进度宽度
     *
     * @param progressWidth
     */
    public void setProgressWidth(int progressWidth) {
        this.progressWidth = progressWidth;
    }

    public void setSnoreList(List<Medix_Pub_Sync_SleepDetail> list, long startDate, long endDate) {
        this.sleepDetailList = list;
        this.startDate = startDate;
        this.endDate = endDate;
        invalidate();

    }

    /**
     * 设置速度文字大小
     *
     * @param textSize
     */
    public void setTextSize(int textSize) {
        this.textSize = textSize;
    }

    /**
     * 设置文字
     */
    public void setTime(String startTime, String endTime) {

        this.startTime = startTime;
        this.endTime = endTime;


    }

    /**
     * 设置单位文字大小
     *
     * @param hintSize
     */
    public void setHintSize(int hintSize) {
        this.hintSize = hintSize;
    }

    /**
     * 设置单位文字
     *
     * @param hintString
     */
    public void setUnit(String hintString) {
        this.hintString = hintString;
        invalidate();
    }

    /**
     * 设置直径大小
     *
     * @param diameter
     */
    public void setDiameter(int diameter) {
        this.diameter = dipToPx(diameter);
    }

    /**
     * 为进度设置动画
     *
     * @param last
     * @param current
     */
    private void setAnimation(float last, final float current, int length) {
        progressAnimator = ValueAnimator.ofFloat(last, current);
        progressAnimator.setDuration(length);
        progressAnimator.setTarget(currentAngle);
        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // currentAngle= (float) animation.getAnimatedValue();
                currentAngle = (Float) animation.getAnimatedValue();
                curValues = currentAngle / k;
                if (curValues == currentValues2) {
                    isMoveEnd = false;
                }
            }
        });
        progressAnimator.addListener(new AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
                // TODO Auto-generated method stub

                // Log.e("name", "onAnimationStart  ");
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                // TODO Auto-generated method stub

                // Log.e("name", "onAnimationRepeat  ");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // TODO Auto-generated method stub

                isLoadCount++;
                if (isLoadCount == 1) {
                    isLoadEnd = true;
                }
                // Log.e("name", "onAnimationEnd  isLoadCount::" + isLoadCount);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                // Log.e("name", "onAnimationCancel  ");

            }
        });
        progressAnimator.start();
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    private int dipToPx(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }


    /**
     * 得到屏幕宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    public void setIsShowCurrentSpeed(boolean isShowCurrentSpeed) {
        this.isShowCurrentSpeed = isShowCurrentSpeed;
    }

    public void startCustomAnimation(){
        this.startAnimation(anim);
    }
    public class BarAnimation extends Animation {

        public BarAnimation() {
        }
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if (interpolatedTime < 1.0f) {
                mSweepAnglePer =  interpolatedTime * sweepAngle;

            } else {
                mSweepAnglePer = sweepAngle;

            }
            postInvalidate();
        }
    }
}
